package com.sinoglobal.ningxia.thread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Handler;
import android.os.Message;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
/**
 * @author ty
 * @createdate 2012-11-3 下午4:59:51
 * @Description: 异步下载 
 */
public class DownloadThread implements Runnable{
	private String url;
	private Handler handler;
	
	public DownloadThread(String url,Handler handler){
		this.url=url;
		this.handler=handler;
	}
	
	@Override
	public void run() {
		HttpClient client = new DefaultHttpClient(); 
		try{
		HttpGet httpGet = new HttpGet();  
		httpGet.setURI(new URI(url));  
//		httpGet.addHeader("Accept-Encoding", "identity");
		HttpResponse response = client.execute(httpGet);
		HttpEntity entity  = response.getEntity();  
		int statusCode = response.getStatusLine().getStatusCode();
		if(statusCode==HttpStatus.SC_OK){
			float length = entity.getContentLength();
			ItktLog.d("=======>length"+length+"getAllHeaders"+response.getAllHeaders());
			InputStream is = entity.getContent();
			FileOutputStream fileOutputStream = null;
			if (is != null) {
				File file = new File(FlyApplication.DOWNLOAD_CLIENT_PATH);
				fileOutputStream = new FileOutputStream(file);
				byte[] buf = new byte[1024];
				int ch = -1;
				float count = 0;
				while ((ch = is.read(buf)) != -1) {
					fileOutputStream.write(buf, 0, ch);
					count += ch;
					sendMsg(MContants.DOWNLOAD_PROCESS_LOADING,(int) (count*100/length));
				}
			}
			sendMsg(MContants.DOWNLOAD_PROCESS_COMPLETE,0);
			fileOutputStream.flush();
			if (fileOutputStream != null) {
				fileOutputStream.close();
			}
		}else{
			sendMsg(MContants.DOWNLOAD_PROCESS_NO,0);
		}
		}catch (Exception e) {
			sendMsg(MContants.DOWNLOAD_PROCESS_ERROR,0);
		}finally{
			client.getConnectionManager().shutdown();
		}
	}
	
	private void sendMsg(int flag,int c) {
		Message msg = new Message();
		msg.what = flag;
		msg.arg1=c;
		handler.sendMessage(msg);
	}
}
